# -*- coding: utf-8 -*-

from GKModel.Advertisement import Advertisement
from GKModel.BaseModel import BaseModel
from GKModel.Category import CATEGORY_AD_AREA
from GKModel.Category import Category
from GKModel.Client import Client
from GKModel.Subject import Subject
from GKModel.Tutor import Tutor


class Index(BaseModel):
    AD_KEY = 'MiniProgram'
    TUTOR_KEY = 'System'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.__client = Client(**kwargs)
        self.__category = Category(**kwargs)
        self.__advertisement = Advertisement(**kwargs)
        self.__tutor = Tutor(**kwargs)
        self.__subject = Subject(**kwargs)

        if 'client_token' in kwargs:
            self.__client_token = kwargs['client_token']
        else:
            self.__client_token = None

    def __query_top_carousel(self):
        category = self.__category.query_by_key_name(CATEGORY_AD_AREA, Index.AD_KEY, 'Carousel')
        top_carousel = []
        result, next_start_primary_key = self.__advertisement.query_by_cid(category['cid'])

        top_carousel.extend(result)
        while next_start_primary_key is not None:
            result, next_start_primary_key = self.__advertisement.query_by_cid(category['cid'])
            top_carousel.extend(result)

        return top_carousel

    def __query_golden_tutor(self):
        golden_tutors, next_start_primary_key = self.__tutor.query_tutor_list(
            tutor_type='golden',
            limit=2
        )
        return golden_tutors

    def __query_hot_subject(self):
        hot_subjects = []
        result, next_start_primary_key = self.__subject.query_subjects('hot')
        hot_subjects.extend(result)
        while next_start_primary_key is not None:
            result, next_start_primary_key = self.__subject.query_subjects(
                'hot',
                next_start_primary_key=next_start_primary_key
            )
            hot_subjects.extend(result)
        return hot_subjects

    def get_index(self):
        client_token = self.__client.update_token()
        top_carousel = self.__query_top_carousel()
        golden_tutors = self.__query_golden_tutor()
        hot_subjects = self.__query_hot_subject()

        data = {
            'top_carousel': top_carousel,
            'golden_tutors': golden_tutors,
            'hot_subjects': hot_subjects
        }

        return data, client_token


def new(**kwargs) -> Index:
    return Index(**kwargs)
